package processor

import (
	"gitee.com/Luna-CY/hui-hui/internal/logger"
)

func (cls *Processor) keepalive() {
	cls.mutex.RLock()
	defer cls.mutex.RUnlock()

	for _, application := range cls.application {
		if StateStarted == application.state {
			continue
		}

		if application.quiting {
			continue
		}

		if (StateStartFailed == application.state || StateRunError == application.state) && application.restart {
			logger.GetLogger().Sugar().Infof("进程管理器: 应用异常重启: %s", application.name)

			if err := cls.start(application); nil != err {
				logger.GetLogger().Sugar().Errorf("进程管理器: 重启应用失败，应用: %s，失败原因: %s", application.name, err)
			}

			continue
		}

		if nil != application.c && nil != application.c.ProcessState && application.c.ProcessState.Exited() {
			if application.restart {
				logger.GetLogger().Sugar().Infof("进程管理器: 应用异常重启: %s", application.name)

				if err := cls.start(application); nil != err {
					logger.GetLogger().Sugar().Errorf("进程管理器: 重启应用失败，应用: %s，失败原因: %s", application.name, err)
				}
			}
		}
	}
}
